/*
 * FriendRewardResource.cpp
 *
 *  Created on: 2013. 9. 6.
 *      Author: mega@gamevil.com
 */

#include "../User.h"
#include "FriendRewardResource.h"
#include "../NUtil/Utils.h"

namespace ProjectZ { namespace NResource {

FriendRewardResource::FriendRewardResource()
{
	pFriendRewardAndroid	= new FriendRewardData;
	pFriendRewardIOS		= new FriendRewardData;
}

FriendRewardResource::~FriendRewardResource()
{
	delete pFriendRewardAndroid;
	delete pFriendRewardIOS;
}

bool FriendRewardResource::LoadResource()
{
	if (false == pFriendRewardAndroid->LoadResource(MARKET_GOOGLE, SC_KAKAO_GOOGLE))
		return false;

	if (false == pFriendRewardIOS->LoadResource(MARKET_IOS, SC_KAKAO_IOS))
		return false;

	return true;
}

FriendRewardData::Flyweight * FriendRewardResource::GetFly(int company, int saleCode, FriendRewardData::Key & clsKey)
{
	NUtil::MarketType marketType = NUtil::GetMarketType(company, saleCode);

	switch (marketType)
	{
	case NUtil::MarketType::AD_KAKAO:
		return pFriendRewardAndroid->GetFly(clsKey);

	case NUtil::MarketType::IOS_KAKAO:
		return pFriendRewardIOS->GetFly(clsKey);

	default:
		return NULL;
	}

	return NULL;
}


FriendRewardData::~FriendRewardData()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<DATATREE::value_type>);
}

bool FriendRewardData::LoadResource(int company, int saleCode)
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery(" SELECT * FROM web_friend_reward WHERE company=%d AND sale_cd=%d", company, saleCode);

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	while( clsAuto->Next() )
	{
		int tmpCompany, tmpSaleCode;
		FriendRewardData::Flyweight * pFly = new FriendRewardData::Flyweight;

		clsAuto->GetRecord() >> tmpCompany >> tmpSaleCode
				>> pFly->_TYPE >> pFly->_SUB_TYPE >> pFly->_FRIEND_CNT
				>> pFly->_ITEM_TID >> pFly->_ITEM_SHEET >> pFly->_VALUE
				>> pFly->_IMG_URL_DEFAULT >> pFly->_IMG_URL;

		clsFlyTree[FriendRewardData::Key(pFly->_TYPE, pFly->_SUB_TYPE)] = pFly;
	}

	return true;
}

FriendRewardData::Flyweight * FriendRewardData::GetFly(FriendRewardData::Key & clsKey)
{
	auto iter = clsFlyTree.find(clsKey);

	if( iter == clsFlyTree.end() )
		return NULL;
	else
		return iter->second;
}

} /* NResource */ } /* ProjectZ */

